<template>
  <div class="image-display-test">
    <h2>图片显示测试</h2>
    
    <!-- 测试输入 -->
    <div class="test-section">
      <h3>测试图片路径</h3>
      <el-input
        v-model="testImagePath"
        placeholder="输入图片路径，如: uploads/01a1910"
        style="width: 400px; margin-bottom: 10px;"
      />
      <el-button @click="testImageDisplay" type="primary">测试显示</el-button>
    </div>

    <!-- 显示结果 -->
    <div class="result-section" v-if="testImagePath">
      <h3>显示结果</h3>
      <div class="image-container">
        <div class="image-info">
          <strong>原始路径:</strong> {{ testImagePath }}
        </div>
        <div class="image-info">
          <strong>构建的URL:</strong> {{ constructedUrl }}
        </div>
        <div class="image-info">
          <strong>加载状态:</strong> 
          <span :class="loadStatus">{{ loadStatusText }}</span>
        </div>
        
        <div class="image-preview">
          <img 
            v-if="constructedUrl"
            :src="constructedUrl"
            @load="handleImageLoad"
            @error="handleImageError"
            alt="测试图片"
            class="test-image"
          />
          <div v-else class="no-image">请输入图片路径</div>
        </div>
      </div>
    </div>

    <!-- 调试信息 -->
    <div class="debug-section">
      <h3>调试信息</h3>
      <el-button @click="showDebugInfo" type="info">显示调试信息</el-button>
      <div v-if="debugInfo" class="debug-content">
        <pre>{{ JSON.stringify(debugInfo, null, 2) }}</pre>
      </div>
    </div>

    <!-- 常见路径测试 -->
    <div class="common-paths-section">
      <h3>常见路径测试</h3>
      <div class="path-list">
        <div 
          v-for="(path, index) in commonPaths" 
          :key="index" 
          class="path-item"
          @click="testPath(path)"
        >
          <span class="path-text">{{ path }}</span>
          <span class="path-status" :class="pathStatuses[index]">
            {{ pathStatuses[index] === 'loading' ? '加载中...' : 
               pathStatuses[index] === 'success' ? '成功' : 
               pathStatuses[index] === 'error' ? '失败' : '未测试' }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

// 配置后端服务器地址（用于图片访问）
const BACKEND_SERVER_URL = 'http://localhost:5265'

const testImagePath = ref('')
const constructedUrl = ref('')
const loadStatus = ref('')
const loadStatusText = ref('')
const debugInfo = ref<any>(null)

// 常见路径测试
const commonPaths = ref([
  'uploads/outbound/44f4aeb4-d2eb-4405-92b4-8ad3d083510a.png', // 你实际上传的图片
  'uploads/01a1910',
  'uploads/01a1910.jpg',
  'uploads/01a1910.png',
  '01a1910',
  '01a1910.jpg',
  '01a1910.png'
])

const pathStatuses = ref<string[]>(new Array(commonPaths.value.length).fill(''))

// 获取图片URL（复制自OutboundOrder.vue的逻辑）
const getImageUrl = (url: string): string => {
  if (!url) {
    console.log('getImageUrl: 空URL')
    return ''
  }

  console.log('getImageUrl 输入:', url)

  // 如果是blob URL，检查是否有效
  if (url.startsWith('blob:')) {
    const blobMatch = url.match(/blob:https?:\/\/[^\/]+\/([a-f0-9-]+)/)
    if (!blobMatch) {
      console.warn('无效的blob URL格式:', url)
      return ''
    }
    console.log('getImageUrl: 返回blob URL:', url)
    return url
  }

  // 如果是data URL，直接返回
  if (url.startsWith('data:')) {
    console.log('getImageUrl: 返回data URL:', url)
    return url
  }

  // 如果是完整URL，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    console.log('getImageUrl: 返回完整URL:', url)
    return url
  }

  // 如果是后端返回的文件路径，尝试多种可能的路径格式
  if (url.includes('uploads/') || url.includes('outbound/') || url.includes('.png') || url.includes('.jpg') || url.includes('.jpeg')) {
    // 尝试多种可能的路径格式
    const possiblePaths = [
      // 直接使用后端服务器地址（因为图片在后端服务器上）
      `${BACKEND_SERVER_URL}/${url}`, // 直接拼接，保持完整路径
      `${BACKEND_SERVER_URL}/uploads/${url.replace(/^uploads\//, '')}`,
      // 尝试添加常见扩展名
      `${BACKEND_SERVER_URL}/uploads/${url.replace(/^uploads\//, '')}.jpg`,
      `${BACKEND_SERVER_URL}/uploads/${url.replace(/^uploads\//, '')}.png`,
      `${BACKEND_SERVER_URL}/uploads/${url.replace(/^uploads\//, '')}.jpeg`,
      `${BACKEND_SERVER_URL}/${url}.jpg`,
      `${BACKEND_SERVER_URL}/${url}.png`,
      `${BACKEND_SERVER_URL}/${url}.jpeg`,
      // 前端服务器路径（作为备选）
      `${window.location.origin}/${url}`, // 直接拼接，保持完整路径
      `${window.location.origin}/uploads/${url.replace(/^uploads\//, '')}`,
      `${window.location.origin}/api/uploads/${url}`,
      `${window.location.origin}/static/uploads/${url}`,
      `${window.location.origin}/public/uploads/${url}`,
      // 添加更多可能的路径
      `${window.location.origin}/images/${url}`,
      `${window.location.origin}/assets/${url}`,
      `${window.location.origin}/files/${url}`,
      `${window.location.origin}/media/${url}`,
      `${window.location.origin}/upload/${url}`,
      `${window.location.origin}/uploaded/${url}`,
      `${window.location.origin}/uploads/outbound/${url.replace(/^uploads\//, '')}`,
      `${window.location.origin}/api/upload/${url}`,
      `${window.location.origin}/api/file/${url}`,
      `${window.location.origin}/api/media/${url}`
    ]

    console.log('getImageUrl: 原始路径:', url)
    console.log('getImageUrl: BACKEND_SERVER_URL:', BACKEND_SERVER_URL)
    console.log('getImageUrl: window.location.origin:', window.location.origin)
    console.log('getImageUrl: 可能的路径:', possiblePaths)
    console.log('getImageUrl: 返回第一个路径:', possiblePaths[0])

    // 返回第一个可能的路径，让浏览器尝试加载
    return possiblePaths[0]
  }

  // 其他情况，尝试作为相对路径处理
  console.log('getImageUrl: 返回相对路径:', url)
  return url
}

// 测试图片显示
const testImageDisplay = () => {
  if (!testImagePath.value) {
    ElMessage.warning('请输入图片路径')
    return
  }

  loadStatus.value = 'loading'
  loadStatusText.value = '加载中...'
  constructedUrl.value = getImageUrl(testImagePath.value)
  
  console.log('测试图片路径:', testImagePath.value)
  console.log('构建的URL:', constructedUrl.value)
}

// 处理图片加载成功
const handleImageLoad = () => {
  loadStatus.value = 'success'
  loadStatusText.value = '加载成功'
  console.log('图片加载成功:', constructedUrl.value)
}

// 处理图片加载失败
const handleImageError = () => {
  loadStatus.value = 'error'
  loadStatusText.value = '加载失败'
  console.warn('图片加载失败:', constructedUrl.value)
}

// 测试常见路径
const testPath = (path: string) => {
  const index = commonPaths.value.indexOf(path)
  if (index === -1) return

  pathStatuses.value[index] = 'loading'
  
  const url = getImageUrl(path)
  const img = new Image()
  
  img.onload = () => {
    pathStatuses.value[index] = 'success'
    console.log(`路径 ${path} 加载成功:`, url)
  }
  
  img.onerror = () => {
    pathStatuses.value[index] = 'error'
    console.warn(`路径 ${path} 加载失败:`, url)
  }
  
  img.src = url
}

// 显示调试信息
const showDebugInfo = () => {
  debugInfo.value = {
    testImagePath: testImagePath.value,
    constructedUrl: constructedUrl.value,
    loadStatus: loadStatus.value,
    backendServerUrl: BACKEND_SERVER_URL,
    windowLocationOrigin: window.location.origin,
    userAgent: navigator.userAgent,
    timestamp: new Date().toISOString()
  }
}
</script>

<style scoped>
.image-display-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
}

.result-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 8px;
}

.image-container {
  margin-top: 15px;
}

.image-info {
  margin-bottom: 10px;
  padding: 8px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.image-preview {
  margin-top: 15px;
  text-align: center;
}

.test-image {
  max-width: 300px;
  max-height: 300px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  object-fit: contain;
}

.no-image {
  width: 300px;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  background: #fafafa;
}

.debug-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.debug-content {
  margin-top: 15px;
  padding: 15px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow-x: auto;
}

.debug-content pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
}

.common-paths-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 8px;
}

.path-list {
  margin-top: 15px;
}

.path-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin-bottom: 8px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.path-item:hover {
  background: #f5f5f5;
  border-color: #409eff;
}

.path-text {
  font-family: monospace;
  color: #303133;
}

.path-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.path-status.loading {
  background: #e6f7ff;
  color: #1890ff;
}

.path-status.success {
  background: #f6ffed;
  color: #52c41a;
}

.path-status.error {
  background: #fff2f0;
  color: #ff4d4f;
}

.loading {
  color: #1890ff;
}

.success {
  color: #52c41a;
}

.error {
  color: #ff4d4f;
}
</style>
